<template>
    <view class="abslrtb flex-column a-center wrap">
        <u-navbar title="注册信息" />
        <view class="flex tabs mb30">
            <view @click="tab('student')" class="flex-1 flex aj-center" :class="tabIndex == 'student' && 'active'">
                <text class="fs30 fw600 " :class="tabIndex == 'student' && 'curtext'">我是学生</text>
            </view>
            <view @click="tab('teacher')" class="flex-1 flex aj-center" :class="tabIndex == 'teacher' && 'active'">
                <text class="fs30 fw600 " :class="tabIndex == 'teacher' && 'curtext'">我是老师</text>
            </view>
        </view>
        <view class="form" style="margin-top: 0;">
            <u-form label-position="left" label-width="150rpx" :model="userInfo" :rules="rules" ref="formRef">
                <!-- 教师姓名 -->
                <u-form-item label="姓名" prop="teacherName" :border-bottom="true" v-if="tabIndex === 'teacher'" required>
                    <u-input v-model="userInfo.teacherName" placeholder="请输入姓名" :border="false" clearable>
                        <template #prefix>
                            <u-icon name="account" size="20" color="#2979ff"></u-icon>
                        </template>
                    </u-input>
                </u-form-item>
                <!-- 昵称 -->
                <u-form-item label="昵称" prop="nickName" :border-bottom="true" required>
                    <u-input v-model="userInfo.nickName" placeholder="请输入昵称" :border="false" clearable>
                        <template #prefix>
                            <u-icon name="account" size="20" color="#2979ff"></u-icon>
                        </template>
                    </u-input>
                </u-form-item>

                <!-- 手机号 -->
                <u-form-item label="手机号" prop="phone" :border-bottom="true" required>
                    <u-input v-model="userInfo.phone" placeholder="请输入手机号" :border="false" clearable type="number">
                        <template #prefix>
                            <u-icon name="phone" size="20" color="#2979ff"></u-icon>
                        </template>
                    </u-input>
                </u-form-item>

                <!-- 密码 -->
                <u-form-item label="密码" prop="password" :border-bottom="true" required>
                    <u-input :type="isPasswordVisible ? 'text' : 'password'" v-model="userInfo.password"
                        placeholder="请输入密码" :border="false" clearable>
                        <template #prefix>
                            <u-icon name="lock" size="20" color="#2979ff"></u-icon>
                        </template>
                        <template #suffix>
                            <u-icon name="eye" size="20" color="#2979ff" v-if="!isPasswordVisible"
                                @click="isPasswordVisible = true"></u-icon>
                            <u-icon name="eye-off" size="20" color="#2979ff" v-else
                                @click="isPasswordVisible = false"></u-icon>
                        </template>
                    </u-input>
                </u-form-item>

                <!-- 教师类型 -->
                <u-form-item label="教师类型" prop="teacherType" :border-bottom="true" v-if="tabIndex === 'teacher'"
                    required>
                     <picker mode="selector" range-key="text" :clearabled="true" :range="teacherTypeList"
                        :value="currentTeacherTypeIndex"
                        @change="(e) => userInfo.teacherType = teacherTypeList[e.detail.value]?.teacherType">
                         <view>{{ getTeacherTypeText(userInfo.teacherType) }}</view>
                    </picker>
                </u-form-item>

                <!-- 所属学校 -->
                <u-form-item label="所属学校" prop="schoolName" :border-bottom="true" v-if="tabIndex === 'teacher'"
                    required>
                    <picker mode="selector" range-key="text" :clearabled="true" :range="schoolList"
                        :value="currentSchoolIndex"
                        @change="(e) => userInfo.schoolName = schoolList[e.detail.value]?.schoolId">
                         <view>{{ getSchoolText(userInfo.schoolName) }}</view>
                    </picker>
                </u-form-item>

                <!-- 教学科目 -->
                <u-form-item label="教学科目" prop="subjects" :border-bottom="true" v-if="tabIndex === 'teacher'" required>
                    <picker mode="selector" range-key="text" :clearabled="true" :range="subjectList"
                        :value="currentSubjectIndex"
                        @change="(e) => userInfo.subjects = subjectList[e.detail.value]?.subjectId">
                         <view>{{ getSubjectText(userInfo.subjects) }}</view>
                    </picker>
                </u-form-item>
                <!-- 当前年级 -->
                <u-form-item label="当前年级" prop="currentGrade" :border-bottom="true" v-if="tabIndex === 'student'" required>
                    <picker mode="selector" range-key="text" :clearabled="true" :range="gradeList"
                        :value="currentGradeIndex"
                        @change="(e) => userInfo.currentGrade = gradeList[e.detail.value]?.gradeId">
                         <view>{{ getGradeText(userInfo.currentGrade) }}</view>
                    </picker>
                </u-form-item>
            </u-form>
        </view>

        <view class="btns" @click="submitForm">
            <view class="qbtn">
                <text class="btn-text-color fs30">确认</text>
            </view>
        </view>
        <!-- <view class="bottom">
			
		</view> -->
    </view>
</template>

<script setup lang="ts">
import uniReq from '@/api/uniReq';
import { setToken } from '@/utils/auth';
import { onLoad } from '@dcloudio/uni-app';
import { ref, reactive, onMounted } from 'vue';

// 表单实例引用
const formRef = ref<any>(null);
const show = ref(false);

// 表单数据（与 u-form 的 model 绑定）
const userInfo = reactive({
    teacherName: '', // 教师姓名（仅教师）
    nickName: '',        // 昵称
    phone: '',       // 手机号
    password: '',    // 密码
    teacherType: '1', // 教师类型（仅教师）
    schoolName: '',  // 所属学校（仅教师）
    subjects: '',    // 教学科目（仅教师）
    currentGrade: ''        // 当前年级（仅学生）
});

const gradeList = ref([]);
const schoolList = ref([]);
const subjectList = ref([]);
const teacherTypeList = ref([
    { teacherType: '10', text: '在职教师' },
    { teacherType: '20', text: '优秀毕业生' },
    { teacherType: '30', text: '退休老师' }
])
// 计算当前年级的索引（用于picker的value）
const currentGradeIndex = computed(() => {
  if (!userInfo.currentGrade) return 0
  const index = gradeList.value.findIndex(item => item.gradeId === userInfo.currentGrade)
  return index !== -1 ? index : 0
})
// 计算当前学校的索引（用于picker的value）
const currentSchoolIndex = computed(() => {
  if (!userInfo.schoolName) return 0
  const index = schoolList.value.findIndex(item => item.schoolName === userInfo.schoolName)
  return index !== -1 ? index : 0
})
// 计算当前教学科目的索引（用于picker的value）
const currentSubjectIndex = computed(() => {
  if (!userInfo.subjects) return 0
  const index = subjectList.value.findIndex(item => item.subjects === userInfo.subjects)
  return index !== -1 ? index : 0
})
// 计算当前教师类型的索引（用于picker的value）
const currentTeacherTypeIndex = computed(() => {
  if (!userInfo.teacherType) return 0
  const index = teacherTypeList.value.findIndex(item => item.teacherType === userInfo.teacherType)
  return index !== -1 ? index : 0
})
// 根据教师类型ID获取显示文本
const getTeacherTypeText = (teacherType) => {
  if (!teacherType) return '请选择教师类型'
  const teacherTypeItem = teacherTypeList.value.find(item => item.teacherType === teacherType)
  return teacherTypeItem ? teacherTypeItem.text : '请选择教师类型'
}
// 根据教学科目ID获取显示文本
const getSubjectText = (subjectId) => {
  if (!subjectId) return '---'
  const subject = subjectList.value.find(item => item.subjectId === subjectId)
  return subject ? subject.text : '请选择'
}
// 根据学校ID获取显示文本
const getSchoolText = (schoolId) => {
  if (!schoolId) return "---"
  const school = schoolList.value.find(item => item.schoolId === schoolId)
  return school ? school.text : '请选择'
}
// 根据年级ID获取显示文本
const getGradeText = (gradeId) => {
  if (!gradeId) return "请选择"
  const grade = gradeList.value.find(item => item.gradeId === gradeId)
  return grade ? grade.text : '请选择'
}

// 获取下拉列表
const getGradeList = async () => {
    try {
        const res = await uniReq({
            url: '/grade/find-grade-id-and-name',
            method: 'get',
            params: {
                pageNum: 1,
                pageSize: 100
            }
        })
        if (res.status === 200) {
            gradeList.value = res.data.map(item => ({
                gradeId: item.gradeId,
                text: item.name
            })) || [];
        }
    } catch (error) {
        console.error('获取年级列表失败:', error);
    }
}
const getSchoolList = async () => {
    try {
        const res = await uniReq({
            url: '/school/find-Name-Id',
            method: 'get',
            params: {
                pageNum: 1,
                pageSize: 100
            }
        })
        if (res.status === 200) {
            schoolList.value = res.data.map(item => ({
                schoolId: item.schoolId,
                text: item.name
            })) || [];
        }
    } catch (error) {
        console.error('获取学校列表失败:', error);
    }
}
const getSubjectList = async () => {
    try {
        const res = await uniReq({
            url: '/subject/select-subject-nam-and-id',
            method: 'get',
            params: {
                pageNum: 1,
                pageSize: 100
            }
        })
        if (res.status === 200) {
            subjectList.value = res.data.map(item => ({
                subjectId: item.subjectId,
                text: item.name
            })) || [];
        }
    } catch (error) {
        console.error('获取科目列表失败:', error);
    }
}

// 密码可见性控制
const isPasswordVisible = ref(false);

// 教师类型选择弹窗控制
const showTeacherTypes = ref(false);

// Tab 切换（学生/教师）
const tabIndex = ref<'student' | 'teacher'>('student');

// 表单验证规则（uView Pro 推荐直接定义 rules，而非 setRules 方法）
const rules = reactive({
    teacherName: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '请输入昵称', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
    ],
    teacherType: [
        { required: true, message: '请选择教师类型', trigger: 'change' }
    ],
    schoolName: [
        { required: true, message: '请选择所属学校', trigger: 'change' }
    ],
    subjects: [
        { required: true, message: '请选择教学科目', trigger: 'change' }
    ],
});


const verifyCode = ref('');
onLoad((options: any) => {
    getGradeList();
    getSchoolList();
    getSubjectList();
    verifyCode.value = options.code || '';
})

// 表单提交
const submitForm = async () => {
    console.log(userInfo);

    try {
        const valid = await formRef.value.validate();

        if (valid) {
            // 验证通过，执行注册逻辑
            if (tabIndex.value === 'teacher') {
                uniReq({
                    url: '/auth/teacher-register',
                    method: 'POST',
                    data: {
                        verifyCode: verifyCode.value,
                        ...userInfo
                    }
                }).then((res: any) => {
                    uni.hideLoading();
                    if (res.status === 200) {
                        setToken(res.data.currentToken);
                        uni.setStorageSync('userInfo', res.data);
                        uni.showToast({
                            title: res.message || '注册成功',
                            icon: 'success'
                        })
                        // 跳转到首页
                        uni.switchTab({
                            url: '/pages/index/index'
                        })
                    } else {
                        uni.showToast({
                            title: res.message || '注册失败',
                            icon: 'none'
                        })
                    }
                })
            } else {
                uniReq({
                    url: '/auth/student-register',
                    method: 'POST',
                    data: {
                        verifyCode: verifyCode.value,
                        ...userInfo
                    }
                }).then((res: any) => {
                    uni.hideLoading();
                    if (res.status === 200) {
                        setToken(res.data.currentToken);
                        uni.setStorageSync('userInfo', res.data);
                        uni.showToast({
                            title: res.message || '注册成功',
                            icon: 'success'
                        })
                        // 跳转到登录页面
                        uni.switchTab({
                            url: '/pages/index/index'
                        })
                    } else {
                        uni.showToast({
                            title: res.message || '注册失败',
                            icon: 'none'
                        })
                    }
                })
            }
            // 后续可添加接口请求代码
        }
    } catch (error) {
        // 验证失败，uView Pro 会自动提示错误信息
        console.log('表单验证失败：', error);
    }
};

// Tab 切换事件（清空无关字段）
const tab = (index: 'student' | 'teacher') => {
    tabIndex.value = index;
    if (index === 'student') {
        // 切换到学生，清空教师相关字段
        userInfo.teacherName = '';
        userInfo.teacherType = '';
        userInfo.schoolName = '';
        userInfo.subjects = '';
    } else {
        // 切换到教师，清空学生相关字段
        userInfo.grade = '';
    }
    // 清空表单验证状态
    //   formRef.value?.clearValidate();
};
</script>

<style scoped lang="scss">
@import url("./style/qui_weex.scss");
@import url("./style/skin06.scss");

.qradio {
    transform: scale(0.6);
    color: #FF5A5F;
}

.TeacherSel {
    width: 100%;
    height: 40px;
    line-height: 40px;
    padding: 0 10px;
    border: none;
    border-radius: 5px;
    background-color: #fff;
}

.picker-item {
    padding: 10rpx 0;
    //透明背景
    background: #E0EEFF;
    border-radius: 8rpx;
    font-size: 28rpx;
    color: #333;
    min-width: 120rpx;
    text-align: center;
}
</style>